package handlers

import (
	"car-data-hub/cache"
	"car-data-hub/models"
	"car-data-hub/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录信息不能为空",
		})
		return
	}

	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登陆",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户或密码不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5Str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁两小时",
			})
		} else {
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "密码错误",
			})
			return
		}
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		  where user_roles.uid=1
	*/
	var list []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid=?", uid).
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		  WHERE role_nodes.rid=1
	*/
	var list []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid=?", rid).
		Debug().
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	Offset := (page - 1) * size
	/*
		     	 SELECT
			  car_orders.id as OrderId,
			  cars.car_no as CarNo,
			  cars.car_name as CarName,
			  cars.car_type as CarType,
			  car_orders.order_no as OrderNo,
			  car_orders.order_name as OrderName,
			  car_orders.order_price as OrderPrice
			FROM
			  car_orders
			  LEFT JOIN cars ON car_orders.cid = cars.id
			  where car_orders.id=2
	*/
	var list []models.CarOrderList

	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select(
				"car_orders.id as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_type as CarType",
				"car_orders.order_no as OrderNo",
				"car_orders.order_name as OrderName",
				"car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Offset(Offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	models.DB.Model(&models.CarOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  list,
		"total": total,
	})
	return
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var list models.CarOrderList

	redis_key := "car_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select(
				"car_orders.id as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_type as CarType",
				"car_orders.order_no as OrderNo",
				"car_orders.order_name as OrderName",
				"car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Where("car_orders.id=?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}
